package sealed_generator.card;

import java.util.ArrayList;
import java.util.Comparator;

public class CardComparator implements Comparator<Card> {
	
	String method;

	/**Method codes:
	 * C = color
	 * M = mana cost
	 * Y = card type
	 * E = edition
	 * P = power
	 * T = toughness
	 * R = rarity
	 * 
	 * Note: all sorts will be filtered at the last level by Name (and then edition if they have the same name)
	 * For a name only sort, pass an empty string
	 */
	public CardComparator(String method){
		this.method = method.toUpperCase();
	}
	
	public int compare(Card c1, Card c2) {
		for(int i = 0; i < method.length(); i++){
			char filter = method.charAt(i);
			int compareResult = 0;
			switch(filter){
			case 'C':compareResult = colorCompare(c1, c2); break;
			case 'M':compareResult = manaCostCompare(c1, c2); break;
			case 'Y':compareResult = cardTypeCompare(c1, c2); break;
			case 'E':compareResult = editionCompare(c1, c2); break;
			case 'P':compareResult = powerCompare(c1, c2); break;
			case 'T':compareResult = toughnessCompare(c1, c2); break;
			case 'R':compareResult = rarityCompare(c1, c2); break;
			}
			if (compareResult != 0)
				return compareResult;
		}
		int finalCompare = nameCompare(c1, c2);
		if (finalCompare == 0){
			finalCompare = editionCompare(c1, c2);
		}
		return finalCompare;
	}
	
	private int colorCompare(Card c1, Card c2){
		ArrayList<Color> c1Colors = c1.getColors();
		ArrayList<Color> c2Colors = c2.getColors();
		//If both are mono colored, just use Color.compareTo()
		if ((c1Colors.size() == 1) && (c2Colors.size() == 1))
			return c1Colors.get(0).compareTo(c2Colors.get(0));
		
		//Mono colored comes before gold and colorless
		if ((c1Colors.size() == 1) && (c2Colors.size() != 1))
			return -1;
		if ((c1Colors.size() != 1) && (c2Colors.size() == 1))
			return 1;
		
		//Gold comes becore colorless
		if ((c1Colors.size() > 1) && (c2Colors.size() == 0))
			return -1;
		if ((c1Colors.size() == 0) && (c2Colors.size() > 1))
			return 1;
		
		//Both colorless or both gold
		return 0;
	}
	
	private int manaCostCompare(Card c1, Card c2){
		return c1.getManaCost().compareTo(c2.getManaCost());
	}
	
	private int nameCompare(Card c1, Card c2){
		return c1.getName().compareTo(c2.getName());
	}
	
	private int editionCompare(Card c1, Card c2){
		return c1.getSet().getName().compareTo(c2.getSet().getName());
	}
	
	private int cardTypeCompare(Card c1, Card c2){
		int compare = c1.getType().compareTo(c2.getType());
		if (compare == 0){
			compare = c1.getSuperType().compareTo(c2.getSuperType());
		}
		return compare;
	}
	
	private int powerCompare(Card c1, Card c2){
		return c1.getPower().compareTo(c2.getPower());
	}
	
	private int toughnessCompare(Card c1, Card c2){
		return c1.getToughness().compareTo(c2.getToughness());
	}

	private int rarityCompare(Card c1, Card c2){
		return c1.getRarity().compareTo(c2.getRarity());
	}
}
